package information;

import com.alibaba.fastjson.JSONObject;
import com.sun.media.jfxmedia.events.VideoTrackSizeListener;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author 司啸飞
 * @create 2021-05-17 10:57
 */
public class MyUrlDispose {

    /**
     * 获取到url中的json源码
     * @param api
     * @throws Exception
     */
    private void getJsonCode(UpInformation upData, String api) throws Exception {
        URL url = new URL(api);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        // 获取到url中的json代码,写入到io流
        InputStream is = httpUrl.getInputStream();
        // 以UTF-8的编码形式写进字符缓冲流
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        // 创建字符串
        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        is.close();
        br.close();

        extractData(upData, sb.toString());
    }

//    private void getJsonCode(UpInformation upData, String api) throws Exception {
//        File file = new File(api);
//        FileInputStream is = new FileInputStream(file);
//        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
//        StringBuffer sb = new StringBuffer();
//        String line;
//        while ((line = br.readLine()) != null) {
//            sb.append(line);
//        }
//        is.close();
//        br.close();
//        // 调用方法
//        extractData(upData, sb);
//    }

    /**
     * 因为需要用的数据都会被存在key:"data" 中,所有需要提取出来
     * @param upData
     * @param sb
     */
    private void extractData(UpInformation upData, String sb) {
        JSONObject jo = JSONObject.parseObject(sb.toString());
        jo = jo.getJSONObject("data");
        upData.setJsonObjectAll(jo);
    }

    /**
     * 使用IO流获取头像(face)
     * @param upData
     */
    private void getImage(UpInformation upData, String fileName) throws Exception {
        //new一个文件对象用来保存图片，默认保存当前工程根目录
        File file = new File(".\\image");
        File facePath = new File(file+"\\face.jpg");
        // 判断目录是否存在,不存在直接创建
        if (file.exists() == false) {
            file.mkdirs();
        }

        // 获取头像属性为直链
        String face = upData.getJsonObject("face");
        URL url = new URL(face);
        // 打开url
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置url请求为get
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        // 创建输入流
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);

        //创建输出流
        FileOutputStream outStream = new FileOutputStream(facePath);
        //写入数据
        outStream.write(data);

        outStream.close();
    }

    /**
     * 获取到图片
     * @param inStream
     * @return
     * @throws Exception
     */
    private byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


    /**
     * 调用所有方法
     * @param upData
     * @param mid
     * @throws Exception
     */
    public void sumData(UpInformation upData, String mid) throws Exception {
        this.getJsonCode(upData, APIData.URL_RELATION1+mid+APIData.URL_RELATION2);
        this.getJsonCode(upData, APIData.URL_SPACE+mid);
        this.getImage(upData, "face.jpg");
        this.getImage(upData, "top_photo.png");
    }




    public static void main(String[] args) throws Exception {
        MyUrlDispose my = new MyUrlDispose();
        my.sumData(UpInformation.getUpInformation(), "0");
        UpInformation up = UpInformation.getUpInformation();
        System.out.println(up.getJsonObject("name"));
        System.out.println(up.getJsonObject("face"));
    }
}
class APIData {
    /** 后面+mid为完整SPACE */
    static final String URL_SPACE = "http://api.bilibili.com/x/space/acc/info?mid=";
    /** URL_RELATION1+mid+URL_RELATION2 */
    static final String URL_RELATION1 = "https://api.bilibili.com/x/relation/stat?vmid=";
    static final String URL_RELATION2 = "&jsonp=jsonp";
}
